--
-- DESCRIPTION
--
-- @COMPANY **
-- @AUTHOR **
-- @DATE ${date} ${time}
--

---@type CBP_Base_C

local M = Class()

local Screen = require "Screen"
local Debug = require "Debug"
local Const = require "Const"

function M:Initialize(Initializer)
	self.IsDead = false
	self.BodyDuration = 6.0
	self.BoneName = nil
	local Health = 100
	self.Health = Health
	self.MaxHealth = Health
end

function M:ReceiveBeginPlay()
--   Screen.Print(string.format("Health ... %d", self.Health ))
	local Weapon = self:SpawnWeapon()
	if Weapon then
		Weapon:K2_AttachToComponent(self.Mesh, Const.SSP_WeaponSocket, UE.EAttachmentRule.SnapToTarget, UE.EAttachmentRule.SnapToTarget, UE.EAttachmentRule.SnapToTarget)
		self.Weapon = Weapon
	end
end

function M:SpawnWeapon()
	return nil
end

function M:StartFire_Server_RPC()
	self:StartFire_Multicast()
end

function M:StartFire_Multicast_RPC()
	if self.Weapon then
		self.Weapon:StartFire()
	end
end

function M:StopFire_Server_RPC()
	self:StopFire_Multicast()
end

function M:StopFire_Multicast_RPC()
	if self.Weapon then
		self.Weapon:StopFire()
	end
end

function M:ReceiveAnyDamage(Damage, DamageType, InstigatedBy, DamageCauser)
  -- Screen.Print('ReceiveAnyDamage: CBP_Base')
	if not self.IsDead then
		local Health = self.AttrComp.Health - Damage
		self.AttrComp.Health = math.max(Health, 0)
    -- Screen.Print(string.format("Hp: %d", self.AttrComp.Health))
    self:UpdateUI()

		if Health <= 0.0 then
			self:Died_Multicast(DamageType)
      local co = coroutine.create(M.Destroy)
      coroutine.resume(co, self, self.BodyDuration)
		end
	end
end

function M:UpdateUI()
  return nil
end

function M:Died_Multicast_RPC(DamageType)
	self.IsDead = true
  self.CapsuleComponent:SetCollisionEnabled(UE.ECollisionEnabled.NoCollision)
  self:ChangeToRagdoll()

	self:StopFire()
	local Controller = self:GetController()
	if Controller then
		Controller:UnPossess()
	end
end

function M:Destroy(Duration)
  -- Screen.Print("CBP Destroy...")

	UE.UKismetSystemLibrary.Delay(self, Duration)
	if not self:IsValid() then
		return false
	end

	if self.Weapon then
		self.Weapon:K2_DestroyActor()
	end
	self:K2_DestroyActor()
end

function M:ChangeToRagdoll()
	self.Mesh:SetCollisionProfileName("Ragdoll")
	self.Mesh:SetSimulatePhysics(true)
end

return M
